<template>
	<div class="inspection-records" v-if="visible && recordId">
		<div class="header">
			<span class="title">检查记录</span>
			<div class="header-actions">
				<button class="close-button" @click="closeDialog" title="关闭">
					<i class="el-icon-close"></i>
				</button>
				<!-- <button class="export-button" @click="exportPDF" title="导出PDF">
					<i class="el-icon-document"></i> 导出PDF
				</button> -->
			</div>
		</div>

		<div class="content">
			<div class="inspection-info displayFlexBet">
				<div class="info-row">
					<div class="info-item mr20">
						<span class="font16">{{ getRecordValue('serveEntName') }}</span>
					</div>

					<div class="value mr20">
						<span class="color888 mr5">时间</span>
						<span>{{ getRecordValue('inspectionTimeStr') }}</span>
					</div>
					<div class="value mr20">
						<span class="color888 mr5">检查单位</span>
						<span>{{ getRecordValue('serveEntName') }}</span>
					</div>

					<div class="value">
						<span class="color888 mr5">检查人</span>
						<span>{{ getRecordValue('executorName') }}</span>
					</div>
				</div>
				<div class="displayFlex">
					<div style="width: 90px;line-height: 31px;background: #3A3EF4;border-radius: 2px;"
						class="colorfff textCenter font14 mr20 point" @click="completeInspection">完成检查</div>
					<div @click="exportPDF"
						style="width: 90px;line-height: 31px;background: #FFFFFF;border-radius: 2px;border: 1px solid #3A3EF4;color:#3A3EF4"
						class="textCenter font14 point">导出PDF</div>
				</div>
			</div>

			<div class="bgfff">
				<div class="inspection-section" v-for="(section, index) in inspectionData.details" :key="index">
					<h3 class="section-title">检查项目 {{ section.mainTypeName }}</h3>

					<div class="inspection-item" v-for="(item, itemIndex) in section.list" :key="itemIndex">
						<div class="item-header">
							<span class="item-number">{{ itemIndex + 1 }}.</span>
							<span class="item-title">{{ item.subTypeName }}</span>
							<span class="status-tag" :class="getStatusClass(item)">
								{{ item.status === 0 ? '正常记录' : '整改项' }}
							</span>
						</div>
						<div class="images-grid" v-if="hasImages(item)">
							<div class="image-box" v-for="(imageUrl, imageIndex) in item.imageUrls" :key="imageIndex">
								<img :src="getImageUrl(imageUrl)" alt="检查图片" class="inspection-image" />
							</div>
						</div>
						<div class="item-notes">
							记录：{{ item.remark }}
						</div>
					</div>
				</div>
			</div>

			<!-- 	<div class="actions">
				<button class="complete-button" @click="completeInspection">完成检查</button>
			</div> -->
		</div>
	</div>
</template>

<script>
	import html2pdf from 'html2pdf.js';

	// that变量，用于在异步回调中引用组件实例
	let that;

	// 图片查看URL
	const fileViewUrl =
		'https://www.weifeibangbang.com/wfbb-webupload/service/sys/file/upload/view?appKey=5da5441f62e48aedc7a3853ffc75c2db&prodID=gf&fileID=';

	export default {
		name: 'InspectionRecords',
		props: {
			visible: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				recordId: '',
				// 检查记录数据
				inspectionData: {
					record: {},
					details: []
				},
				// 图片基础URL
				fileViewUrl: fileViewUrl
			};
		},
		watch: {
			visible(newVal) {
				if (newVal) {
					this.recordId = localStorage.getItem("recordId")
					if (!this.recordId) {
						// 当没有记录ID时，通知父组件显示"暂无记录"提示并关闭弹窗
						this.$message.error('暂无检查记录');
						this.$emit('no-record');
						this.$emit('close');
					} else {
						// 当组件显示且有记录ID时，获取检查详情
						this.getInspectionDetail();
					}
				}
			}
		},
		mounted() {
			that = this; // 保存组件实例引用

			// 初始化时，如果visible为true但没有recordId，也需要发送no-record事件
			if (this.visible && !this.recordId) {
				this.$emit('no-record');
				this.$emit('close');
			}
		},
		methods: {
			// 安全获取记录值
			getRecordValue(field) {
				if (this.inspectionData && this.inspectionData.record && this.inspectionData.record[field] !== undefined) {
					return this.inspectionData.record[field];
				}
				return '';
			},

			// 获取状态样式类
			getStatusClass(item) {
				if (item && typeof item.status !== 'undefined') {
					return item.status === 0 ? 'normal' : 'abnormal';
				}
				return 'normal';
			},

			// 检查是否有图片
			hasImages(item) {
				return item && item.imageUrls && Array.isArray(item.imageUrls) && item.imageUrls.length > 0;
			},

			// 获取检查详情
			getInspectionDetail() {
				if (!this.recordId) {
					this.$message.warning('暂无记录');
					this.$emit('no-record');
					this.$emit('close');
					return;
				}

				that.ajax({
					url: '/gov/inspection/det/getInspectionDetail',
					data: {
						recordId: this.recordId
					},
					contentType: 'application/x-www-form-urlencoded',
					success: function(result) {
						if (result.status == 1) {
							that.inspectionData = result.data;
							console.log('检查详情数据:', that.inspectionData);
						} else {
							that.$message.error('获取检查详情失败');
						}
					},
					error: function(error) {
						console.error('获取检查详情失败:', error);
						that.$message.error('获取检查详情失败，请重试');
					}
				});
			},

			// 获取图片URL
			getImageUrl(fileId) {
				return fileId ? this.fileViewUrl + fileId : '';
			},

			// 关闭对话框
			closeDialog() {
				this.$emit('close');
			},

			// 导出PDF
			exportPDF() {
				// 设置导出选项
				const options = {
					margin: 10,
					filename: `检查记录-${new Date().toLocaleDateString()}.pdf`,
					image: {
						type: 'jpeg',
						quality: 0.98
					},
					html2canvas: {
						scale: 2,
						useCORS: true
					},
					jsPDF: {
						unit: 'mm',
						format: 'a4',
						orientation: 'portrait'
					}
				};

				// 获取内容部分
				const content = this.$el.querySelector('.content');

				// 导出为PDF
				html2pdf().from(content).set(options).save().then(() => {
					this.$message({
						message: 'PDF导出成功',
						type: 'success'
					});
				}).catch(error => {
					console.error('PDF导出失败:', error);
					this.$message.error('PDF导出失败，请重试');
				});
			},

			// 完成检查
			completeInspection() {
				if (!this.recordId) {
					this.$message.warning('暂无记录');
					return;
				}

				that.ajax({
					url: '/gov/inspection/record/completeInspectionStatus',
					data: {
						recordId: this.recordId
					},
					contentType: 'application/x-www-form-urlencoded',
					success: function(result) {
						if (result.status == 1) {
							that.$message.success('检查已完成');
							// 通知父组件初始化数据
							that.$emit('inspection-completed');
							that.closeDialog();

							// 添加loading状态
							const loading = that.$loading({
								lock: true,
								text: '正在跳转企业详情页...',
								spinner: 'el-icon-loading',
								background: 'rgba(255, 255, 255, 0.7)'
							});

							setTimeout(function() {
								window.open("http://116.62.120.142/bbep-gov/#/enterPrise/detail");
								loading.close(); // 关闭loading
							}, 1000);
						} else {
							that.$message.error('完成检查失败');
						}
					},
					error: function(error) {
						console.error('完成检查失败:', error);
						that.$message.error('完成检查失败，请重试');
					}
				});
			}
		}
	};
</script>

<style scoped lang="scss">
	.inspection-records {
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		width: 80%;
		max-width: 90vw;
		max-height: 90vh;
		background-color: #F8F8F8;
		border-radius: 8px;
		box-shadow: 0 2px 20px rgba(0, 0, 0, 0.2);
		z-index: 9999;
		display: flex;
		flex-direction: column;
		overflow: hidden;

		.header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 0 15px;
			height: 50px;
			background-color: #3a3ef4;
			color: #fff;

			.title {
				font-size: 16px;
				font-weight: bold;
			}

			.header-actions {
				display: flex;
				align-items: center;
				gap: 15px;

				.close-button,
				.export-button {
					display: flex;
					align-items: center;
					background-color: rgba(255, 255, 255, 0.2);
					border: none;
					color: white;
					padding: 4px 8px;
					border-radius: 3px;
					cursor: pointer;
					font-size: 12px;

					&:hover {
						background-color: rgba(255, 255, 255, 0.3);
					}

					i {
						margin-right: 4px;
					}
				}

				.close-button i {
					margin-right: 0;
				}
			}
		}

		.content {
			padding: 20px;
			overflow-y: auto;
			max-height: calc(90vh - 50px);

			.inspection-info {
				margin-bottom: 20px;
				padding: 15px;
				background: #fff;

				.info-row {
					display: flex;
					align-items: center;
				}

				.info-item {
					display: flex;

					.label,
					.value {
						font-size: 14px;
					}
				}
			}

			.inspection-section {
				margin-bottom: 30px;
				background: #fff;
				padding: 15px;

				.section-title {
					font-size: 14px;
					color: #333;
					margin-bottom: 15px;
					font-weight: normal;
				}

				.inspection-item {
					border-radius: 4px;
					padding: 15px;
					margin-bottom: 15px;

					.item-header {
						display: flex;
						align-items: center;
						margin-bottom: 15px;

						.item-number {
							margin-right: 5px;
							color: #333;
						}

						.item-title {
							margin-right: 5px;
							color: #333;
						}

						.status-tag {
							padding: 2px 8px;
							border-radius: 20px;
							font-size: 12px;
							color: white;

							&.normal {
								background-color: #67c23a;
							}

							&.abnormal {
								background-color: #f56c6c;
							}
						}
					}

					.images-grid {
						display: flex;
						flex-wrap: wrap;
						gap: 10px;
						margin-bottom: 15px;

						.image-box {
							width: 120px;
							height: 100px;
							background-color: #eee;
							border-radius: 4px;
							overflow: hidden;

							.inspection-image {
								width: 100%;
								height: 100%;
								object-fit: cover;
							}
						}
					}

					.item-notes {
						color: #666;
						font-size: 13px;
						line-height: 1.5;
					}
				}
			}

			.actions {
				display: flex;
				justify-content: center;
				margin-top: 20px;

				.complete-button {
					background-color: #3a3ef4;
					color: #fff;
					border: none;
					border-radius: 4px;
					padding: 8px 30px;
					cursor: pointer;
					font-size: 14px;

					&:hover {
						background-color: darken(#3a3ef4, 10%);
					}
				}
			}
		}
	}
</style>